package com.wsoft.hr.pm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.bpm.enums.ApproveStatus;
import com.wsoft.bpm.query.mapping.ExtraBusinessDataQuery;
import com.wsoft.bpm.service.ActivityCallAble;
import com.wsoft.bpm.service.WorkFlowService;
import com.wsoft.constant.redis.HrPmRedisKeyConstant;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.RedisService;
import com.wsoft.entity.BaseEntity;
import com.wsoft.hr.pm.entity.*;
import com.wsoft.hr.pm.enums.HrProcessFlowStageEnum;
import com.wsoft.hr.pm.enums.ProcessKeyEnum;
import com.wsoft.hr.pm.enums.WorkFlowBusinessDataEnum;
import com.wsoft.hr.pm.manager.*;
import com.wsoft.hr.pm.mapper.HrPmGradeMapper;
import com.wsoft.hr.pm.query.grade.*;
import com.wsoft.hr.pm.query.grade.member.HrPmGradeMemberListQuery;
import com.wsoft.hr.pm.query.grade.member.HrPmGradeMemberUpdateQuery;
import com.wsoft.hr.pm.query.grade.member.cycle.HrPmGradeMemberCycleListQuery;
import com.wsoft.hr.pm.query.grade.org.HrPmGradeOrgListQuery;
import com.wsoft.hr.pm.service.IHrPmCycleService;
import com.wsoft.hr.pm.service.IHrPmGradeService;
import com.wsoft.hr.pm.service.sys.IHrOrganizationService;
import com.wsoft.hr.pm.vo.grade.GradeStatisticsVO;
import com.wsoft.hr.pm.vo.grade.GradeStatusVO;
import com.wsoft.hr.pm.vo.grade.MemberCycleScoreVO;
import com.wsoft.hr.pm.vo.sys.HrOrganizationVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author Z001
 * @Date 2025-03-01 08:35:23
 */
@Service
public class HrPmGradeServiceImpl extends ServiceImpl<HrPmGradeMapper, HrPmGradeEntity> implements IHrPmGradeService, ActivityCallAble {

    @Resource
    private HrPmGradeManager gradeManager;
    @Resource
    private HrPmGradeOrgManager gradeOrgManager;
    @Resource
    private HrPmActivityManager activityManager;
    @Resource
    private HrPmMemberTemplateManager memberTemplateManager;
    @Resource
    private HrPmGradeMemberCycleManager memberCycleManager;
    @Resource
    private HrPmGradeMemberManager gradeMemberManager;
    @Resource
    private IHrOrganizationService organizationService;
    @Resource
    private WorkFlowService workFlowService;
    @Resource
    private IHrPmCycleService cycleService;
    @Resource
    private RedisService redisService;


    /**
     * 考核评级-分页查询
     *
     * @param query
     * @return PageInfo
     */
    @Override
    public PageInfo listHrPmGrade(HrPmGradeListQuery query) {
        HrPmGradeListQuery gradeListQuery = new HrPmGradeListQuery();
        gradeListQuery.setName(query.getName());
        gradeListQuery.setEnable(1);
        //查询grade信息
        List<HrPmGradeEntity> gradeList = gradeManager.list(gradeListQuery);
        List<Long> gradeIdList = gradeList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        Map<Long, HrPmGradeEntity> gradeMap = gradeList.stream().collect(Collectors.toMap(HrPmGradeEntity::getId, Function.identity()));

        HrPmGradeOrgListQuery param = new HrPmGradeOrgListQuery();
        //查询gradeOrg表
        param.setGradeIdList(gradeIdList);
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<HrPmGradeOrgEntity> gradeOrgList = gradeOrgManager.list(param);
        PageInfo pageInfo = PageInfo.of(gradeOrgList);

        List<HrPmGradeOrgEntity> list = pageInfo.getList();
        List<GradeStatusVO> collect = list.stream().map(item -> {
            HrPmGradeEntity gradeEntity = gradeMap.get(item.getGradeId());
            GradeStatusVO statusVO = Convert.convert(GradeStatusVO.class, gradeEntity);
            statusVO.setStatus(item.getStatus());
            statusVO.setGradeOrgId(item.getId());
            statusVO.setHrOrgId(item.getHrOrgId());
            return statusVO;
        }).collect(Collectors.toList());
        pageInfo.setList(collect);
        return pageInfo;
    }

    /**
     * 考核评级-获取用户等级列表
     *
     * @param id
     * @return
     */
    @Override
    public PageInfo getMemberGrade(HrPmGradeInfoQuery query) {
        HrPmGradeOrgEntity orgEntity = gradeOrgManager.getById(query.getId());
        HrPmGradeMemberListQuery gradeMemberListQuery = new HrPmGradeMemberListQuery();
        gradeMemberListQuery.setGradeId(orgEntity.getGradeId());
        gradeMemberListQuery.setGradeOrgId(query.getId());
        gradeMemberListQuery.setMemberCodeOrName(query.getName());
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<HrPmGradeMemberEntity> gradeList = gradeMemberManager.list(gradeMemberListQuery);
        if (CollUtil.isEmpty(gradeList)) {
            return PageInfo.of(new ArrayList<>());
        }
        PageInfo pageInfo = PageInfo.of(gradeList);
        List<HrPmGradeMemberEntity> memberEntityList = pageInfo.getList();

        // 将用户ID作为键，用户对象作为值
        Map<Long, HrPmGradeMemberEntity> gradeMemberMap = memberEntityList.stream().collect(Collectors.toMap(HrPmGradeMemberEntity::getId, Function.identity()));

        List<Long> idList = memberEntityList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        HrPmGradeMemberCycleListQuery cycleListQuery = new HrPmGradeMemberCycleListQuery();
        cycleListQuery.setGradeMemberId(idList);
        List<HrPmGradeMemberCycleEntity> cycleList = memberCycleManager.list(cycleListQuery);

        //组装用户分数数组
        List<MemberCycleScoreVO> scoreList = buildScoreList(cycleList, gradeMemberMap);
        List<MemberCycleScoreVO> scoreVoS = groupAndMergeByMemberId(scoreList);
        pageInfo.setList(buildScore(scoreVoS));
        return pageInfo;
    }



    public  List<MemberCycleScoreVO> groupAndMergeByMemberId(List<MemberCycleScoreVO> scoreList) {
        Map<Long, MemberCycleScoreVO> map= new HashMap<>(12);
        for (MemberCycleScoreVO vo : scoreList) {
          if(map.containsKey(vo.getMemberId())){
              MemberCycleScoreVO cycleScoreVO = map.get(vo.getMemberId());
              Map<Long, BigDecimal> scoreMap = cycleScoreVO.getScoreMap();
              scoreMap.putAll(vo.getScoreMap());
              map.put(vo.getMemberId(),cycleScoreVO);
          }else{
              map.put(vo.getMemberId(),vo);
          }
        }
        return new ArrayList<>(map.values());
    }


    @Override
    @GetRedisCache(type = HrPmRedisKeyConstant.GRADE_STATISTICS,
            expire_sec = HrPmRedisKeyConstant.EXPIRED,
            value = RedisKeyConstant.REDIS_SELF)
    public GradeStatisticsVO getGradeStatistics(Long gradeOrgId) {
        // 根据查询条件获取评分组织实体
        HrPmGradeOrgEntity gradeOrg = gradeOrgManager.getById(gradeOrgId);

        // 根据查询条件获取评分实体
        HrPmGradeEntity gradeEntity = gradeManager.getById(gradeOrg.getGradeId());

        // 创建评分成员列表查询对象并设置评分ID
        HrPmGradeMemberListQuery gradeMemberListQuery = new HrPmGradeMemberListQuery();
        gradeMemberListQuery.setGradeId(gradeEntity.getId());
        gradeMemberListQuery.setGradeOrgId(gradeOrgId);
        // 获取评分成员列表
        List<HrPmGradeMemberEntity> gradeList = gradeMemberManager.list(gradeMemberListQuery);
        if (CollUtil.isEmpty(gradeList)) {
            return new GradeStatisticsVO();
        }
        //同一个人的多条数据 按一人统计
        gradeList = gradeList.stream()
                .collect(Collectors.toMap(
                        // 按 memberId 分组
                        HrPmGradeMemberEntity::getMemberId,
                        // 保留原始对象
                        entity -> entity,
                        // 如果 memberId 重复，保留第一个
                        (existing, replacement) -> existing
                ))
                // 获取去重后的值
                .values().stream().collect(Collectors.toList());

        long count = gradeList.stream().filter(item -> StrUtil.isEmpty(item.getGrade())).count();
        List<Map<String, String>> gradeMapList = new ArrayList<>();
        List<Map<String, Object>> hrOrgMapList = new ArrayList<>();
        List<Map<String, Object>> hrPostMapList = new ArrayList<>();
        GradeStatisticsVO vo = new GradeStatisticsVO();
        // 如果所有评分成员的等级都已填写，进行统计
        if (count == 0) {
            gradeMapList = statisticsGrade(gradeList);
            hrOrgMapList = statisticsHrOrg(gradeList);
            hrPostMapList = statisticsHrPost(gradeList);
        }
        // 提取评分成员的ID列表
        List<Long> idList = gradeList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        HrPmGradeMemberCycleListQuery cycleListQuery = new HrPmGradeMemberCycleListQuery();
        cycleListQuery.setGradeMemberId(idList);
        // 获取评分成员周期列表
        List<HrPmGradeMemberCycleEntity> cycleList = memberCycleManager.list(cycleListQuery);
        // 提取周期ID和周期名称的映射关系
        Map<Long, String> cycleNameMap = cycleList.stream()
                .collect(Collectors.toMap(
                        HrPmGradeMemberCycleEntity::getCycleId,
                        HrPmGradeMemberCycleEntity::getCycleName,
                        // 如果有重复的周期ID，保留已有的值
                        (existing, replacement) -> existing
                ));
        vo.setGradeAllMap(gradeMapList);
        vo.setHrOrgMap(hrOrgMapList);
        vo.setPostMap(hrPostMapList);
        vo.setCycleNameMap(cycleNameMap);
        vo.setGradeEntity(gradeEntity);
        vo.setGradeOrgEntity(gradeOrg);
        return vo;
    }


    /**
     * 新增-考核评级
     *
     * @param query
     * @return
     */
    @Override
    public boolean insertHrPmGrade(HrPmGradeInsertQuery query) {
        HrPmGradeEntity gradeEntity = Convert.convert(HrPmGradeEntity.class, query);
        gradeEntity.setHrOrgIds(StrUtil.join(StrUtil.COMMA, query.getHrOrgIds()));
        gradeEntity.setEnable(0);
        return gradeManager.save(gradeEntity);
    }

    /**
     * 启用考核
     *
     * @param query
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean enableGrade(HrPmGradeEnableQuery query) {
        HrPmGradeEntity gradeEntity = gradeManager.getById(query.getId());
        if (null == gradeEntity || 1 == gradeEntity.getEnable()) {
            Asserts.fail("[hr.pm.target.status.error]");
        }

        //保存评级相关内容
        int count = saveGradeOrg(gradeEntity);

        //判断评级下 是否有对应的活动
        if(count == 0){
            Asserts.fail("[hr.pm.grade.count.error]");
        }

        gradeEntity.setEnable(1);
        gradeManager.updateById(gradeEntity);
        return true;
    }

    /**
     * 更新考核信息
     *
     * @param query
     * @return
     */
    @Override
    public boolean updateHrPmGrade(HrPmGradeUpdateQuery query) {
        HrPmGradeEntity gradeEntity = gradeManager.getById(query.getId());
        if (gradeEntity.getEnable() != 0) {
            //只能未启用的时候 才能修改信息
            Asserts.fail("[hr.pm.target.status.error]");
        }
        HrPmGradeEntity convert = Convert.convert(HrPmGradeEntity.class, query);
        convert.setHrOrgIds(StrUtil.join(StrUtil.COMMA, query.getHrOrgIds()));
        convert.setEnable(0);
        return gradeManager.updateById(convert);
    }

    /**
     * 更新-用户考核等级
     *
     * @param query
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMemberGrade(HrPmMemberGradeUpdateQuery query) {
        if (CollUtil.isEmpty(query.getGradeList())) {
            return true;
        }

        Set<Long> memberIdSet = new HashSet<>();
        //更新考评等级
        List<HrPmGradeMemberUpdateQuery> gradeList = query.getGradeList();
        if (CollUtil.isNotEmpty(gradeList)) {
            for (HrPmGradeMemberUpdateQuery gradeQuery : gradeList) {
                HrPmGradeMemberEntity entity = gradeMemberManager.getById(gradeQuery.getId());
                if(!memberIdSet.contains(entity.getMemberId())){
                    gradeMemberManager.batchUpdateGrade(entity.getGradeId(),entity.getMemberId(),gradeQuery.getGrade());
                    memberIdSet.add(entity.getMemberId());
                }
            }
        }
        redisService.del(HrPmRedisKeyConstant.GRADE_STATISTICS + query.getId());
        return true;
    }

    /**
     * 删除-考核评级
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        HrPmGradeOrgEntity gradeOrg = gradeOrgManager.getById(id);
        checkStatus(gradeOrg);

        //级联删除下级组织
        List<HrOrganizationVO> childOrg = organizationService.getChildOrg(gradeOrg.getHrOrgId(), true);
        List<Long> hrOrgIdList = childOrg.stream().map(HrOrganizationVO::getId).collect(Collectors.toList());
        gradeOrgManager.removeByGradeId(gradeOrg.getGradeId(), hrOrgIdList);

        return true;
    }


    /**
     * 提交
     *
     * @param query
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submit(HrPmMemberGradeUpdateQuery query) {
        //更新等级
        updateMemberGrade(query);
        HrPmGradeOrgEntity gradeOrg = gradeOrgManager.getById(query.getId());
        Long hrOrgId = gradeOrg.getHrOrgId();

        //校验是否都已经评分
        checkGrade(gradeOrg);

        //校验工作流
        checkStatus(gradeOrg.getStatus());

        //工作流
        String randomString = RandomUtil.randomString(8);
        gradeOrg.setBusinessCode(randomString);
        gradeOrgManager.updateById(gradeOrg);

        WorkFlowBusinessDataEnum dataEnum = WorkFlowBusinessDataEnum.GRADE_DETAIL;
        ExtraBusinessDataQuery extraBusinessDataQuery = new ExtraBusinessDataQuery(dataEnum.getBusinessType(), dataEnum.getBusinessValue(), null, null);
        workFlowService.startProcess(ProcessKeyEnum.GRADE_ORG.getProcessKey(), ProcessKeyEnum.GRADE_ORG.getTableName(), randomString, extraBusinessDataQuery, new HashMap(1));

        //该组织及下组织 全部赋值当前工作流状态
        updateChildWfStatus(hrOrgId, query.getId(), ApproveStatus.APPROVING.getValue(), true);


        return true;
    }

    @Override
    public PageInfo<HrPmGradeEntity> workList(HrPmGradeListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        query.setEnable(0);
        List<HrPmGradeEntity> list = gradeManager.list(query);
        return PageInfo.of(list);
    }

    @Override
    public HrPmGradeEntity getInfo(Long id) {
        return gradeManager.getById(id);
    }

    @Override
    public boolean workDelete(Long id) {
        return gradeManager.removeById(id);
    }

    // ################################## 私有方法  ##################################

    /**
     * 更新下级的所有工作流状态
     *
     * @param hrOrgId
     * @param gradeId
     */
    private void updateChildWfStatus(Long hrOrgId, Long gradeId, Integer status, boolean isSubmit) {
        List<HrOrganizationVO> childOrg = organizationService.getChildOrg(hrOrgId, false);
        if (CollUtil.isEmpty(childOrg)) {
            return;
        }
        List<HrPmGradeOrgEntity> list = gradeOrgManager.getByOrgAndGradeIds(gradeId, childOrg.stream().map(HrOrganizationVO::getId).collect(Collectors.toList()));
        if (isSubmit) {
            //提交的时候需要判断是否有自己还在审批中状态
            //如果是工作流完成回调修改自己,则不需要判断子集是否还在审批中状态
            long count = list.stream().filter(item -> !item.getHrOrgId().equals(hrOrgId)
                    && ApproveStatus.APPROVING.getValue().equals(item.getStatus())).count();

            if (count > 0) {
                //当前状态/子组织状态不正确,无法操作!
                Asserts.fail("[hr.pm.child.status.error]");
            }
        }

        list = list.stream().peek(item -> item.setStatus(status)).collect(Collectors.toList());
        gradeOrgManager.updateBatchById(list);
    }

    /**
     * 校验是否都已经评分
     *
     * @param gradeId
     */
    private void checkGrade(HrPmGradeOrgEntity gradeOrg) {
        //校验评分
        HrPmGradeMemberListQuery query = new HrPmGradeMemberListQuery();
        query.setGradeId(gradeOrg.getGradeId());
        List<HrPmGradeMemberEntity> list = gradeMemberManager.list(query);
        if (CollUtil.isNotEmpty(list)) {
            long count = list.stream().filter(item -> StrUtil.isEmpty(item.getGrade())).count();
            if (count > 0) {
                //还有评分为空的,不能提交
                Asserts.fail("[hr.pm.grade.error]");
            }
        }
    }


    /**
     * 校验状态
     *
     * @param gradeId
     */
    private void checkStatus(HrPmGradeOrgEntity gradeOrg) {
        if (ObjUtil.isEmpty(gradeOrg.getStatus()) || ApproveStatus.APPROVING.getValue().equals(gradeOrg.getStatus())) {
            //工作流审批中的 不能修改
            Asserts.fail("[hr.pm.target.status.error]");
        }
    }


    /**
     * 保存评级相关内容
     *
     * @param query
     * @param gradeId
     */
    public int saveGradeOrg(HrPmGradeEntity gradeEntity) {
        String[] hrOrgIdArr = gradeEntity.getHrOrgIds().split(StrUtil.COMMA);
        if (hrOrgIdArr.length == 0) {
            return 0;
        }
        int count = 0;
        //周期id集合
        String[] cycleIds = gradeEntity.getCycleIds().split(StrUtil.COMMA);
        for (String hrOrgId : hrOrgIdArr) {
            //获取活动下的人员
            int number = convertGradeMemberList(Long.parseLong(hrOrgId), gradeEntity.getId(), cycleIds,count);
            count = count + number;
        }
        return count;
    }

    /**
     * 保存grade 相关表信息
     *
     * @param hrOrgId
     * @param gradeId
     * @param memberList
     * @param childOrgIds
     * @param cycleIds
     */
    private int convertGradeMemberList(Long hrOrgId, Long gradeId, String[] cycleIds,int count) {
        for (String cycleId : cycleIds) {
            int activity = getActivity(hrOrgId, gradeId, cycleId,count);
            count = count + activity;
        }
        return count;
        //获取组织和周期下的活动,并保存相关表信息
//        IntStream.range(0, cycleIds.length).parallel().forEach(item -> getActivity(hrOrgId, gradeId, cycleIds[item]));
    }

    /**
     * 获取周期下的活动
     *
     * @param childOrgId
     * @param hrOrgId
     * @param gradeId
     * @param cycleId
     */
    public int getActivity(Long hrOrgId, Long gradeId, String cycleId,int count) {
        //查询周期和组织id 下的活动
        List<HrPmActivityEntity> activityEntityList = activityManager.getByCycleAndOrg(Convert.toLong(cycleId), hrOrgId, 1);
        for (HrPmActivityEntity activityEntity : activityEntityList) {
            if (null != activityEntity) {
                //查询该活动下人员列表
                List<HrPmMemberTemplateEntity> memberTemplateEntities = memberTemplateManager.getMemberTemplateByQuery(activityEntity.getId(), null);
                if (CollUtil.isEmpty(memberTemplateEntities)) {
                    return 0;
                }
                if(memberTemplateEntities.stream().anyMatch(item -> !HrProcessFlowStageEnum.COMPLETED.getType().equals(item.getState()))){
                    //无法发起评级,有员工尚未走完流程!
                    Asserts.fail("[hr.pm.grade.member.error]");
                }

                //组织下有活动人员 才去新增
                HrPmGradeOrgEntity gradeOrgEntity = new HrPmGradeOrgEntity();
                gradeOrgEntity.setHrOrgId(hrOrgId);
                gradeOrgEntity.setGradeId(gradeId);
                gradeOrgEntity.setStatus(0);
                gradeOrgManager.save(gradeOrgEntity);

                count = count + 1;

                for (HrPmMemberTemplateEntity memberTemplateEntity : memberTemplateEntities) {
                    HrPmGradeMemberEntity convert = Convert.convert(HrPmGradeMemberEntity.class, memberTemplateEntity);
                    convert.setGradeOrgId(gradeOrgEntity.getId());
                    convert.setGradeId(gradeId);
                    convert.setIsRemove(0);
                    convert.setId(null);
                    gradeMemberManager.save(convert);

                    HrPmGradeMemberCycleEntity cycleEntity = new HrPmGradeMemberCycleEntity();
                    cycleEntity.setGradeMemberId(convert.getId());
                    cycleEntity.setCycleId(Long.valueOf(cycleId));
                    HrPmCycleEntity cyEntity = cycleService.getById(Long.valueOf(cycleId));
                    //赋值周期名称
                    cycleEntity.setCycleName(null == cyEntity ? null : cyEntity.getName());
                    cycleEntity.setActivityId(activityEntity.getId());
                    cycleEntity.setMemberTemplateId(memberTemplateEntity.getId());
                    cycleEntity.setScore(memberTemplateEntity.getScore());
                    memberCycleManager.save(cycleEntity);
                }
            }
        }

        return count;
    }

    /**
     * 组织逗号分隔,移除某个组织
     *
     * @param originalStr
     * @param target
     * @return
     */
    public static String removeElement(String originalStr, String target) {
        if (originalStr == null || originalStr.isEmpty()) {
            return originalStr;
        }
        return Arrays.stream(originalStr.split(StrUtil.COMMA))
                .filter(s -> !s.equals(target))
                .collect(Collectors.joining(StrUtil.COMMA));
    }


    /**
     * 统计总的评分
     *
     * @param gradeList
     * @return
     */
    private List<Map<String, String>> statisticsGrade(List<HrPmGradeMemberEntity> gradeList) {
        //分组查询 统计总的
        Map<String, Long> gradeMap = gradeList.stream().collect(Collectors.groupingBy(HrPmGradeMemberEntity::getGrade, Collectors.counting()));
        gradeMap.put("all", (long) gradeList.size());
        return gradeMap.entrySet().stream()
                .map(entry -> {
                    Map<String, String> map = new HashMap<>(2);
                    map.put("gradeName", entry.getKey());
                    map.put("gradeValue", entry.getValue().toString());
                    return map;
                })
                .collect(Collectors.toList());
    }

    /**
     * 按部门统计
     *
     * @param gradeList
     * @return
     */
    private List<Map<String, Object>> statisticsHrOrg(List<HrPmGradeMemberEntity> gradeList) {
        //按照部门名称统计
        Map<String, Map<String, Long>> hrOrgMap = gradeList.stream()
                .collect(Collectors.groupingBy(
                        // 先按hrOrgName分组
                        HrPmGradeMemberEntity::getHrOrgFullName,
                        Collectors.groupingBy(
                                // 再按grade分组
                                HrPmGradeMemberEntity::getGrade,
                                // 统计每组的人数
                                Collectors.counting()
                        )
                ));

        // 在每个hrOrgName下增加all统计
        hrOrgMap.forEach((hrOrgName, gradeCount) -> {
            long total = gradeCount.values().stream().mapToLong(Long::longValue).sum(); // 计算总人数
            gradeCount.put("all", total); // 将总人数放入Map中
        });

        // 转换格式
        return hrOrgMap.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> orgMap = new HashMap<>(2);
                    orgMap.put("orgName", entry.getKey());

                    List<Map<String, String>> valueList = entry.getValue().entrySet().stream()
                            .map(gradeEntry -> {
                                Map<String, String> map = new HashMap<>(2);
                                map.put("gradeName", gradeEntry.getKey());
                                map.put("gradeValue", String.valueOf(gradeEntry.getValue()));
                                return map;
                            })
                            .collect(Collectors.toList());

                    orgMap.put("value", valueList);
                    return orgMap;
                })
                .collect(Collectors.toList());
    }

    /**
     * 按照岗位转换
     *
     * @param gradeList
     * @return
     */
    private List<Map<String, Object>> statisticsHrPost(List<HrPmGradeMemberEntity> gradeList) {
        //按照岗位名称统计
        Map<String, Map<String, Long>> hrPostMap = gradeList.stream()
                .collect(Collectors.groupingBy(
                        // 先按postName分组
                        HrPmGradeMemberEntity::getPostName,
                        Collectors.groupingBy(
                                // 再按grade分组
                                HrPmGradeMemberEntity::getGrade,
                                // 统计每组的人数
                                Collectors.counting()
                        )
                ));

        // 在每个postName下增加all统计
        hrPostMap.forEach((postName, gradeCount) -> {
            long total = gradeCount.values().stream().mapToLong(Long::longValue).sum(); // 计算总人数
            gradeCount.put("all", total); // 将总人数放入Map中
        });

        // 转换格式
        return hrPostMap.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> postMap = new HashMap<>(2);
                    postMap.put("orgName", entry.getKey());

                    List<Map<String, String>> valueList = entry.getValue().entrySet().stream()
                            .map(gradeEntry -> {
                                Map<String, String> map = new HashMap<>(2);
                                map.put("gradeName", gradeEntry.getKey());
                                map.put("gradeValue", String.valueOf(gradeEntry.getValue()));
                                return map;
                            })
                            .collect(Collectors.toList());

                    postMap.put("value", valueList);
                    return postMap;
                })
                .collect(Collectors.toList());
    }

    /**
     * 组装用户分数数组
     *
     * @param cycleList
     * @param gradeMemberMap
     * @return
     */
    private List<MemberCycleScoreVO> buildScoreList(List<HrPmGradeMemberCycleEntity> cycleList, Map<Long, HrPmGradeMemberEntity> gradeMemberMap) {
        // 分组用户分数
        Map<Long, Map<Long, BigDecimal>> groupedData = cycleList.stream()
                .collect(Collectors.groupingBy(
                        HrPmGradeMemberCycleEntity::getGradeMemberId,
                        Collectors.toMap(HrPmGradeMemberCycleEntity::getCycleId,
                                entity -> entity.getScore() != null ? entity.getScore() : BigDecimal.ZERO,
                                (existing, replacement) -> existing)
                ));

        // 组装用户分数数组
        return groupedData.entrySet().stream()
                .map(entry -> {
                    HrPmGradeMemberEntity memberEntity = gradeMemberMap.get(entry.getKey());
                    Map<Long, BigDecimal> scopeMap = entry.getValue();
                    MemberCycleScoreVO cycleScoreVO = Convert.convert(MemberCycleScoreVO.class, memberEntity);
                    cycleScoreVO.setScoreMap(scopeMap);
                    return cycleScoreVO;
                })
                .collect(Collectors.toList());
    }

    /**
     * 校验工作流状态
     * @param status
     */
    private void checkStatus(Integer status){
        if (ApproveStatus.APPROVING.getValue().equals(status) ||
                ApproveStatus.APPROVED.getValue().equals(status) ||
                ApproveStatus.REJECT.getValue().equals(status)) {
            Asserts.fail("[bpm.startProcess.status.submitBlocked]");
        }
    }

    /**
     * 处理分数
     * @param scoreVOS
     * @return
     */
    private List<MemberCycleScoreVO> buildScore(List<MemberCycleScoreVO> scoreVoS){
        for (MemberCycleScoreVO scoreVO : scoreVoS) {
            Map<Long, BigDecimal> scoreMap = scoreVO.getScoreMap();
            BigDecimal reduce = scoreMap.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
            int size = scoreMap.keySet().size();
            scoreVO.setAverageScore(reduce.divide(new BigDecimal(size), 2, RoundingMode.HALF_UP));
        }
        return scoreVoS;
    }

    // ################################## 工作流相关  ##################################

    @Override
    public String getProcessDefKey() {
        return ProcessKeyEnum.GRADE_ORG.getProcessKey();
    }

    @Override
    public void complete(String processDefKey, String processInstanceId, String businessKey) {

        HrPmGradeOrgEntity entity = gradeOrgManager.getByBusinessCode(businessKey);
        //完成修改自己,isSubmit 为false
        updateChildWfStatus(entity.getHrOrgId(), entity.getId(), ApproveStatus.APPROVED.getValue(), false);

    }


}
